package gin_handler

import (
	file_constants "app/app_src/framework/constant/file"
	web_util "app/app_src/framework/util/web"
	"os"
	"strings"

	"github.com/gin-gonic/gin"
)

// 渲染脚本的处理器

func NewRenderScriptHandler(urlPrefix string) gin.HandlerFunc {
	handler := func(ctx *gin.Context) {
		request := ctx.Request
		url := request.URL
		path := url.Path

		if strings.HasPrefix(path, urlPrefix) && strings.HasSuffix(path, file_constants.FILE_SUFFIX_JS) &&
			!strings.HasSuffix(path, file_constants.FILE_SUFFIX_NODE_JS) {
			defer func() {
				if r := recover(); r != nil {
					err, ok := r.(error)

					if !(ok && os.IsNotExist(err)) {
						panic(r)
					}
				}
			}()

			// 移除前缀
			name := strings.TrimPrefix(path, urlPrefix)
			// 渲染脚本
			web_util.RenderScript(ctx, name)
		}
	}

	return handler
}
